<template>
	<view class="restaurant-available-categories-container">
		<common-title :title="titleContent" @clickLeft="backToUpPage" @clickRight="savePage"></common-title>
		<!-- 展示列表 -->
		<restaurant-categories-manage :restaurantCategoryAndDishes="categoryAndDishesData" :onSale="onSale"
									v-if="categoryAndDishesData" @changeStatus="changeStatus" @clickEdit="clickEdit"
		></restaurant-categories-manage>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import { onBeforeRouteLeave } from 'vue-router';
	import { apiGetRestaurantCategoryAndDishes, apiGetRestaurantDishOnSaleByCategoryName, apiPutRestaurantCategoryAndDishesStatus } from '@/utils/apiRestaurant.js';
	//==============================标题===============================
	//标题内容
	const titleContent = ref({
		left:'返回',
		midst:'餐厅-已上架类别',
		right: '保存'
	});
	//返回
	const backToUpPage = () => {
		uni.switchTab({
			url:'/pages/manage/manage'
		});
	};
	// 如果修改数据但未提交，提醒用户提交
	onBeforeRouteLeave((to, from, next) => {
	    // 检查 isEdit 的实际值
	    if (changedStatusCategory.value.length > 0) {
	        // 如果有未保存的修改，显示提示框
	        uni.showModal({
	            title: '提示',
	            content: '是否保存修改？',
	            success: async function (res) {
	                if (res.confirm) {
	
	                    // TODO: 提交修改的逻辑
	                    // 假设有一个函数 submitChanges() 用于提交修改
	                    await savePage();
	
	                    // 提交完成后允许导航
	                    next();
	                } else {
	
	
	                    // TODO: 删除缓存或执行其他逻辑（根据需要）
	                    
	                    // 直接允许导航
	                    next();
	                }
	            }
	            // 在这里不调用 next()，因为需要根据用户的操作来决定
	        });
	    } else {
	        // 如果没有修改，直接允许导航
	        next();
	    }
	});
	//是否修改数据（是否上下架）
	const isEdit = ref(false);
	//保存修改菜品数据
	const savePage = async () => {
		// console.log("保存类别");
		// console.log(changedStatusCategory.value);
		
		if (changedStatusCategory.value.length > 0) {
			let res = await apiPutRestaurantCategoryAndDishesStatus(0, changedStatusCategory.value);
			if (res === '200') {
				//置空被改变的菜品，重新查一次菜品。
				changedStatusCategory.value = [];
				getCategoryAndDishesData();
				uni.removeStorage({
					key: 'cartDishData'
				});
				uni.showToast({
					title:'保存成功',
					icon:'success'
				});
			}
			else {
				uni.showToast({
					title:'保存失败',
					icon:'error'
				});
			}
		}
		else {
			uni.showToast({
				title:'没有数据被修改',
				icon:'none'
			});
		}
	};
	//==============================展示列表===============================
	// 上下架数据
	const onSale = ref(true);
	//承接类别菜品数据
	const categoryAndDishesData = ref();
	//获取上架类别数据
	const getCategoryAndDishesData = async () => {
		let res = await apiGetRestaurantCategoryAndDishes(1);
		// console.log(res);
		categoryAndDishesData.value = res;
		
		// 遍历对象并为每个类别添加 onSale 属性
		for (const category in categoryAndDishesData.value) {
		    categoryAndDishesData.value[category].onSale = true; // 所有类别设置 onSale 为 true
		}
		// console.log(categoryAndDishesData.value);
	}
	getCategoryAndDishesData();
	//==============================操作按钮===============================
	// 定义 changedStatusDishes，初始为空数组
	let changedStatusCategory = ref([]);
	//改变状态
	const changeStatus = async (status, data) => {
		isEdit.value = ! isEdit.value;
		// console.log(status);
		// console.log(data);
		// 查询data下是否有在售菜品
		if (status === true) {
			let resData = await apiGetRestaurantDishOnSaleByCategoryName(data);
			// console.log(resData);
			if (resData.length > 0) {
				uni.showModal({
					content: `类别 ${data} 下有在售菜品，是否将在售菜品同时下架？`,
					success: function (res) {
						if (res.confirm) {
							// console.log(resData);
							categoryAndDishesData.value[data].onSale = false;
							categoryAndDishesData.value[data].forEach(dish => {
								if (resData.includes(dish.id) && dish.status === 1) {
									dish.status = 0; // 更改为 0
								}
							});
							// console.log(data);
							changedStatusCategory.value.push({
								categoryName: data,
								dishIds: resData
							});
							// console.log(changedStatusCategory.value);
						} else if (res.cancel) {
							console.log("取消");

						}
					}
				})
			} else {
				categoryAndDishesData.value[data].onSale = false;
				// console.log(data);
				changedStatusCategory.value.push({
					categoryName: data,
					dishIds: resData
				});
				// console.log(changedStatusCategory.value);
			}
		}else {
			// console.log(data);
			// 记录要还原的操作
			const dishesToRestore = changedStatusCategory.value.find(item => item.categoryName === data)?.dishIds || [];
			
			// 还原菜品的状态
			dishesToRestore.forEach(dishId => {
				const dishToRestore = categoryAndDishesData.value[data].find(dish => dish.id === dishId);
				if (dishToRestore) {
					dishToRestore.status = 1; // 恢复为原状态，假设原状态是 1
				}
			});
			// 使用 filter 删除 categoryName 为 "素食菜单" 的项
			changedStatusCategory.value = changedStatusCategory.value.filter(item => {
			    return item.categoryName !== data;
			});
			categoryAndDishesData.value[data].onSale = true;
			// console.log(changedStatusCategory.value);
		}
		// console.log("改变状态");
	};
	
	// 点击修改
	const clickEdit = (category) => {
		uni.navigateTo({
			url:'/pages/manage/restaurant_manage/restaurant-edit-categories?from=available&categoryName='+category
		})
	};
</script>

<style lang="scss" scoped>

</style>